package com.hncc.kumao.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class MyHttpClientUtils {

    private static ExecutorService executor = Executors.newFixedThreadPool(5);
    
    /**
     * 执行HttpGet请求
     * @param url 请求地址
     * @param headMap 请求头
     * @return 请求结果字符串
     */
    public static String httpGet(String url, Map<String, String> headMap) {
        String responseContent = null;  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try {  
            HttpGet httpGet = new HttpGet(url); 
            if(headMap != null && headMap.size() > 0) {  
                Set<String> keySet = headMap.keySet();  
                for (String key : keySet) {
                    httpGet.addHeader(key, headMap.get(key));  
                }  
            }
            CloseableHttpResponse response = httpclient.execute(httpGet);
            try {  
                System.out.println(response.getStatusLine());
                int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();  
                responseContent = getResponseString(entity);
                System.out.println("debug:" + responseContent);  
                EntityUtils.consume(entity);  
            } finally {  
                response.close();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return responseContent;  
    }
    
    /**
     * 下载文件
     * @param url 地址
     * @param fileSavePath 本地保存路径
     * @param headMap 头信息
     * @param progress 下载进度回调
     */
    public static void download(final String url, final String fileSavePath, 
            final Map<String, String> headMap, final MyDownloadProgress progress) {
        
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try {
            HttpGet httpGet = new HttpGet(url);  
            if(headMap != null && headMap.size() > 0) {  
                Set<String> keySet = headMap.keySet();  
                for (String key : keySet) {  
                    httpGet.addHeader(key, headMap.get(key));  
                }  
            } 
            CloseableHttpResponse response = httpclient.execute(httpGet);  
            try {  
                System.out.println(response.getStatusLine());  
                HttpEntity httpEntity = response.getEntity();  
                long contentLength = httpEntity.getContentLength();  
                InputStream is = httpEntity.getContent();  
                // 根据InputStream 下载文件  
                ByteArrayOutputStream output = new ByteArrayOutputStream();  
                byte[] buffer = new byte[4096];  
                int r = 0;  
                long totalRead = 0;  
                while ((r = is.read(buffer)) > 0) {
                    output.write(buffer, 0, r);  
                    totalRead += r;  
                    if (progress != null) {// 回调进度  
                        progress.onProgress(totalRead, contentLength);  
                    }  
                }  
                //先创建文件夹，防止文件夹不存在报错
                File tempFile = new File(fileSavePath);
                if(!tempFile.exists()) {
                    if(!tempFile.getParentFile().exists()) {
                        tempFile.getParentFile().mkdirs();
                    }
                }
                FileOutputStream fos = new FileOutputStream(fileSavePath);  
                output.writeTo(fos);  
                output.flush();  
                output.close();  
                fos.close();  
                EntityUtils.consume(httpEntity);
            } finally {  
                response.close();
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
            System.out.println("error");
            return;
        } finally {  
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }
        
        /*executor.submit(new Runnable() {
            @Override
            public void run() {}
        });*/
    }
    
    /** 
     * @param entity 
     * @return 将返回结果转化为String 
     * @throws Exception 
     */  
    public static String getResponseString(HttpEntity entity) throws Exception {  
        if (entity == null) {  
            return null;  
        }  
        InputStream is = entity.getContent();  
        StringBuffer strBuf = new StringBuffer();  
        byte[] buffer = new byte[4096];  
        int r = 0;  
        while ((r = is.read(buffer)) > 0) {  
            strBuf.append(new String(buffer, 0, r, "UTF-8"));  
        }  
        return strBuf.toString();  
    }
}